#include "stdafx.h"

#include "MvDisplayHelper.h"
#include "GenICam/System.h"
#include <process.h>

namespace Dahua{

CMvDisplayHelper::CMvDisplayHelper(const GenICam::ICameraPtr& sptrCamera)
	: m_sptrImageConvertHelper(new CMvImageConvertHelper(sptrCamera))
//	, m_displayThread(Infra::CThreadLite::ThreadProc(&CMvDisplayHelper::displayThreadProc, this), "DisplayThread")
	, m_iWidth(0)
	, m_iHeight(0)
    , m_hThread(NULL)
{
	GenICam::IImageFormatControlPtr sptrImageFormatCtrl = GenICam::CSystem::getInstance().createImageFormatControl(sptrCamera);
	GenICam::CIntNode nodeWidth = sptrImageFormatCtrl->width();
	if ( nodeWidth.isValid() )
	{
		int64_t i64Val = 0;
		nodeWidth.getValue(i64Val);
		m_iWidth = (uint32_t)i64Val;
	}

	GenICam::CIntNode nodeHeight = sptrImageFormatCtrl->height();
	if ( nodeHeight.isValid() )
	{
		int64_t i64Val = 0;
		nodeHeight.getValue(i64Val);
		m_iHeight = (uint32_t)i64Val;
	}
}

CMvDisplayHelper::~CMvDisplayHelper()
{
    // 一直等待线程退出 直至线程退出
	// Wait until the thread exits
    destroyThread();
}

unsigned int CMvDisplayHelper::threadProc(void* pParam)
{
	if ( !pParam )
	{
		return -1;
	}

	CMvDisplayHelper* pThis = (CMvDisplayHelper*)pParam;
	pThis->displayThreadProc(NULL);

	return 0;
}

bool CMvDisplayHelper::isValid()
{
	if ( !m_sptrImageConvertHelper )
	{
		return false;
	}

	return m_sptrImageConvertHelper->isValid();
}

bool CMvDisplayHelper::startDisplay(void* pHandle, int iDispalyRate)
{
	if ( !m_sptrImageConvertHelper->isValid() )
	{
		return false;
	}

	bool bOpenRet = m_sptrImageConvertHelper->startConvert(iDispalyRate);
	if ( !bOpenRet )
	{
		return false;
	}

	m_render.setHandle(pHandle);

	bOpenRet = m_render.open(m_iWidth, m_iHeight);
	if ( !bOpenRet )
	{
		m_sptrImageConvertHelper->stopConvert();

		return false;
	}

	m_bRunning = true;
	unsigned threadID = 0;
	m_hThread = (HANDLE)_beginthreadex( NULL, 0, &CMvDisplayHelper::threadProc, (void*)this, 0, &threadID );

	//return m_displayThread.createThread();
	return true;
}

bool CMvDisplayHelper::stopDisplay()
{
    if (m_sptrImageConvertHelper)
    {
        m_sptrImageConvertHelper->stopConvert();
    }
    // 一直等待线程退出 直至线程退出
	// Wait until the thread exits
    destroyThread();

	m_render.close();
	//m_displayThread.destroyThread();

	return true;
}

void CMvDisplayHelper::destroyThread()
{
    m_bRunning = false;

    if (m_hThread != NULL)
    {
        WaitForSingleObject(m_hThread, INFINITE);
        CloseHandle(m_hThread);
        m_hThread = NULL;
    }
}

void CMvDisplayHelper::displayThreadProc(Infra::CThreadLite*)
{
	while ( m_bRunning )
	{
		if (!m_sptrImageConvertHelper )
		{
			continue;;
		}

		CMvImageBufPtr sptrComvertedImage = m_sptrImageConvertHelper->getConvertedImage();
		if ( sptrComvertedImage )
		{
			m_render.display(sptrComvertedImage);
		}		
	}

}

} // namespace Dahua
